import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Crown, MapPin, MessageCircle, UserMinus, Copy, Share } from 'lucide-react'

const API_BASE_URL = 'http://localhost:5000/api'

export default function MembersView({ circle, user }) {
  const [members, setMembers] = useState([])
  const [onlineMembers, setOnlineMembers] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchMembers()
    fetchOnlineMembers()
  }, [circle.id])

  const fetchMembers = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/circles/circles/${circle.id}`)
      const data = await response.json()
      
      if (response.ok) {
        setMembers(data.members || [])
      }
    } catch (err) {
      console.error('获取成员列表失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const fetchOnlineMembers = async () => {
    try {
      const response = await fetch(
        `${API_BASE_URL}/locations/circles/${circle.id}/online-members?user_id=${user.id}`
      )
      const data = await response.json()
      
      if (response.ok) {
        setOnlineMembers(data)
      }
    } catch (err) {
      console.error('获取在线成员失败:', err)
    }
  }

  const isUserOnline = (userId) => {
    return onlineMembers.some(member => member.id === userId)
  }

  const getLastSeen = (userId) => {
    const onlineMember = onlineMembers.find(member => member.id === userId)
    if (onlineMember && onlineMember.last_update) {
      const date = new Date(onlineMember.last_update)
      const now = new Date()
      const diff = Math.floor((now - date) / 1000 / 60) // 分钟差
      
      if (diff < 1) return '刚刚在线'
      if (diff < 60) return `${diff}分钟前在线`
      if (diff < 1440) return `${Math.floor(diff / 60)}小时前在线`
      return date.toLocaleDateString()
    }
    return '离线'
  }

  const handleKickMember = async (memberId) => {
    if (!confirm('确定要踢出这个成员吗？')) return

    try {
      const response = await fetch(`${API_BASE_URL}/circles/circles/${circle.id}/kick`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          admin_id: user.id,
          target_user_id: memberId,
        }),
      })

      if (response.ok) {
        fetchMembers()
      } else {
        const data = await response.json()
        alert(data.error || '踢出成员失败')
      }
    } catch (err) {
      alert('网络错误，请重试')
    }
  }

  const handleCopyInviteCode = () => {
    navigator.clipboard.writeText(circle.invite_code)
    alert('邀请码已复制到剪贴板')
  }

  const handleShareInvite = () => {
    const shareText = `邀请你加入"${circle.name}"圈子，邀请码：${circle.invite_code}`
    if (navigator.share) {
      navigator.share({
        title: 'WalkerRadio 圈子邀请',
        text: shareText,
      })
    } else {
      navigator.clipboard.writeText(shareText)
      alert('邀请信息已复制到剪贴板')
    }
  }

  const isAdmin = (member) => member.role === 'admin'
  const isCurrentUserAdmin = members.some(m => m.user_id === user.id && m.role === 'admin')

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
          <p className="text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col">
      {/* 圈子信息 */}
      <div className="bg-white border-b p-4">
        <div className="text-center mb-4">
          <h2 className="text-lg font-semibold walker-green">{circle.name}</h2>
          {circle.description && (
            <p className="text-sm text-gray-600 mt-1">{circle.description}</p>
          )}
        </div>
        
        {/* 邀请码 */}
        <Card className="bg-gray-50">
          <CardContent className="p-3">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium">邀请码</p>
                <p className="text-xs text-gray-600 font-mono">{circle.invite_code}</p>
              </div>
              <div className="flex space-x-1">
                <Button size="sm" variant="outline" onClick={handleCopyInviteCode}>
                  <Copy className="w-3 h-3" />
                </Button>
                <Button size="sm" variant="outline" onClick={handleShareInvite}>
                  <Share className="w-3 h-3" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 成员列表 */}
      <ScrollArea className="flex-1">
        <div className="p-4 space-y-3">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-medium text-gray-700">
              成员列表 ({members.length})
            </h3>
            <div className="flex items-center space-x-1 text-xs text-gray-500">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <span>{onlineMembers.length}人在线</span>
            </div>
          </div>
          
          {members.map((member) => (
            <Card key={member.id} className="hover:shadow-sm transition-shadow">
              <CardContent className="p-3">
                <div className="flex items-center space-x-3">
                  <div className="relative">
                    <Avatar className="w-12 h-12">
                      <AvatarImage src={member.user?.avatar_url} />
                      <AvatarFallback className="bg-walker-orange text-white">
                        {member.user?.nickname?.charAt(0) || '用'}
                      </AvatarFallback>
                    </Avatar>
                    {isUserOnline(member.user_id) && (
                      <div className="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white"></div>
                    )}
                  </div>
                  
                  <div className="flex-1">
                    <div className="flex items-center space-x-2">
                      <h4 className="font-medium">{member.user?.nickname}</h4>
                      {isAdmin(member) && (
                        <Badge variant="secondary" className="bg-walker-orange/10 text-walker-orange">
                          <Crown className="w-3 h-3 mr-1" />
                          管理员
                        </Badge>
                      )}
                      {member.user_id === user.id && (
                        <Badge variant="outline" className="text-xs">
                          我
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-gray-600">
                      {isUserOnline(member.user_id) ? '在线' : getLastSeen(member.user_id)}
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(member.joined_at).toLocaleDateString()} 加入
                    </p>
                  </div>
                  
                  <div className="flex space-x-1">
                    <Button size="sm" variant="outline">
                      <MessageCircle className="w-3 h-3" />
                    </Button>
                    {isUserOnline(member.user_id) && (
                      <Button size="sm" variant="outline">
                        <MapPin className="w-3 h-3" />
                      </Button>
                    )}
                    {isCurrentUserAdmin && 
                     !isAdmin(member) && 
                     member.user_id !== user.id && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => handleKickMember(member.user_id)}
                        className="text-red-600 hover:text-red-700"
                      >
                        <UserMinus className="w-3 h-3" />
                      </Button>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </ScrollArea>
    </div>
  )
}

